package com.jiang.jetpackdemo.activity

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import kotlinx.android.synthetic.main.activity_play_video.*
import org.salient.artplayer.ui.ControlPanel
import androidx.recyclerview.widget.LinearLayoutManager
import com.jiang.jetpackdemo.R
import com.jiang.jetpackdemo.adapter.MyOnClickListener
import com.jiang.jetpackdemo.adapter.VideoAdapter
import com.jiang.jetpackdemo.model.VideoRecommendInfo
import com.jiang.jetpackdemo.fragment.VideoRecommendFragment
import com.jiang.jetpackdemo.utils.checkIsWifiConnected
import com.jiang.jetpackdemo.utils.downloadFile
import com.jiang.jetpackdemo.viewModel.PlayVideoViewModel
import java.lang.Exception

class PlayVideoActivity : AppCompatActivity() {
    private val viewModel: PlayVideoViewModel by lazy {
        ViewModelProvider(this).get(
            PlayVideoViewModel::class.java
        )
    }
    private val adapter: VideoAdapter by lazy {
        VideoAdapter(
            this,
            viewModel.videoInfoList.value!!,
            R.layout.item_rv_play_video
        )
    }
    private var isTextShow = true
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_play_video)
        initViewModel()
        initView()
        viewModel.getDataFromIntent(intent.getStringExtra(VideoRecommendFragment.INTENT_KEY))
        // getDataFromIntent()
    }

    private fun initView() {
        rv_play.adapter = adapter
        rv_play.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        adapter.setOnClickListener(object :
            MyOnClickListener {
            override fun onClick(pos: Int) {
                val resultBean =
                    if (viewModel.sizeOfVideoInfoList.value!! >= pos) viewModel.videoInfoList.value!![pos] else null
                if (resultBean != null) viewModel.playResultBean.value = resultBean
            }
        })
        iv_hide.setOnClickListener {
            iv_hide.setImageResource(if (isTextShow) R.drawable.ic_baseline_arrow_drop_down else R.drawable.ic_baseline_arrow_drop_up)
            tv_de.visibility = if (isTextShow) View.GONE else View.VISIBLE
            isTextShow = !isTextShow
        }
        iv_star.setOnClickListener { viewModel.addInFavorites(viewModel.playResultBean.value!!) }
        iv_download.setOnClickListener {
            try {
                if (checkIsWifiConnected(this)) {
                    viewModel.downloadVideo()
                } else {
                    AlertDialog.Builder(this)
                        .setTitle("没有连接WiFi是否继续")
                        .setPositiveButton("yes") { dialog, which ->
                            viewModel.downloadVideo()
                        }
                        .setNegativeButton("no") { dialog, which -> dialog.dismiss() }
                        .show()
                }
            } catch (e: Exception) {
                Log.e("Exception", "initView: ${e.localizedMessage}", e)
            }

        }
    }


    private fun initViewModel() {
        viewModel.playResultBean.observe(this,
            Observer { t ->
                startPlay(t)
            })
        viewModel.sizeOfVideoInfoList.observe(this, Observer { adapter.notifyDataSetChanged() })
    }

    private fun startPlay(t: VideoRecommendInfo.ResultBean) {
        val playUrl = t?.data?.playUrl
        if (!playUrl.isNullOrEmpty()) {
            pb_play.visibility = View.VISIBLE
            vv.setUp(playUrl)
            vv.start()
            vv.controlPanel = ControlPanel(this@PlayVideoActivity)
            viewModel.getDataFromNet(
                t.data.id,
                onError = {
                    Toast.makeText(
                        this,
                        "获取推荐失败",
                        Toast.LENGTH_LONG
                    ).show()
                    pb_play.visibility = View.GONE
                }, onFinish = { pb_play.visibility = View.GONE })

            tv_title.text = t?.data?.title ?: "null"
            tv_de.text = t?.data?.description ?: "null"
            //getDataFromNet(t?.data.id)
        }
    }

//    private fun getDataFromIntent() {
//        val intent = intent
//        val stringExtra = intent.getStringExtra(VideoRecommendFragment.INTENT_KEY)
//        if (stringExtra.isNullOrEmpty()) {
//            finish()
//            Toast.makeText(this, "解析失败 :$stringExtra", Toast.LENGTH_LONG).show()
//        } else {
//            viewModel.playResultBean.value =
//                Gson().fromJson(stringExtra, VideoRecommendInfo.ResultBean::class.java)
//        }
//    }

//    private fun getDataFromNet(id: Int) {
//        RetrofitManager.getVideoRecommend(id, object : Callback<VideoRecommendInfo> {
//            override fun onFailure(call: Call<VideoRecommendInfo>, t: Throwable) {
//                Toast.makeText(applicationContext, "获取推荐失败：${t.message}", Toast.LENGTH_LONG).show()
//            }
//
//            override fun onResponse(
//                call: Call<VideoRecommendInfo>,
//                response: Response<VideoRecommendInfo>
//            ) {
//                if (response.isSuccessful) {
//                    val result = response.body()?.result
//                    if (!result.isNullOrEmpty()) {
//                        result.removeAt(0)
//                        viewModel.resetVideoInfoList(result)
//                    } else {
//                        Toast.makeText(
//                            applicationContext,
//                            "获取推荐不成功：${response.code()}",
//                            Toast.LENGTH_LONG
//                        ).show()
//                    }
//                }
//            }
//        })
//
//    }

    override fun onPause() {
        super.onPause()
        vv.pause()
    }

    override fun onDestroy() {
        super.onDestroy()
        vv.pause()
        vv.exitFullscreen()
    }
}
